package org.yibinxueyuan.drawcard.config;

import org.apache.catalina.User;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.yibinxueyuan.drawcard.entity.Userinfo;
import org.yibinxueyuan.drawcard.mapper.UserInfoMapper;

//自定义的UserRealm     继承
public class UserRealm extends AuthorizingRealm {
    @Autowired
    UserInfoMapper userInfoMapper;

    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("执行了授权->doGetAuthorizationInfo");
        //获取当前登录的对象
        Subject subject = SecurityUtils.getSubject();
        Userinfo user = (Userinfo) subject.getPrincipal();//拿到对象

        //授权对象
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        //授权
        info.addStringPermission(user.getPower());

        return info;
    }
    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        System.out.println("执行了授权-> doGetAuthenticationInfo");

        //获取当前用户 不在这里写,控制层写

        //获取用户登录的信息
        UsernamePasswordToken userToken = (UsernamePasswordToken)token;

        //获取用户的信息
        Userinfo userinfo = userInfoMapper.queryUserPasswordByMailbox(userToken.getUsername());

        //判断该邮箱是否存在
        if(userinfo==null){
            return null;        //抛出异常 UnknownAccountException
        }else {
            //密码认证 shiro做  出问题时抛出密码错误的异常
            return new SimpleAuthenticationInfo(userinfo, userinfo.getPassword(), "");
        }
    }
}
